﻿using System;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using QuanLyThuPhiTaiLieu.Entity;
using Telerik.WinControls.UI;
using System.Collections.Generic;

namespace QuanLyThuPhiTaiLieu.Common
{
    public class Utilities
    {
        public static void CloseForm(Form current, Form destination)
        {
            destination.MdiParent = current.MdiParent;
            destination.Dock = DockStyle.Fill;

            current.Hide();
            destination.Show();
            current.Close();
        }

        public static void ResetBackColor(MenuStrip menu, int selectedIndex)
        {
            //foreach (ToolStripItem item in menu.Items)
            //{
            //    item.ResetBackColor();
            //}

            //menu.Items[selectedIndex].BackColor = Color.FromArgb(194, 224, 255);
        }

        public static void ShowMdi(Form current)
        {
            current.Hide();
            var controls = current.MdiParent.Controls.Find("mainPanel", true);

            if(controls.Length > 0)
            {
                controls[0].Visible = true;
            }
            current.Close();
        }

        public static bool OpenForm(Form mdi, string currentFormName)
        {
            if (mdi.ActiveControl != null)
            {
                if (!string.Equals(mdi.ActiveControl.Name, currentFormName, StringComparison.InvariantCulture))
                {
                    if (mdi.ActiveControl is Form)
                    {
                        ((Form)mdi.ActiveControl).Close();
                    }
                    return true;
                }
                return false;
            }
            return true;
        }

        public static string UploadFile(string source, string folderPath)
        {
            var path = string.Empty;

            CheckDirectory(folderPath);
            
            string fullName = Path.GetFileName(source);
            string filePath = Path.Combine(folderPath, fullName);
            int index = 1;

            path = filePath;

            while (File.Exists(filePath))
            {
                string name = Path.GetFileNameWithoutExtension(source);
                string extension = Path.GetExtension(source);

                var temp = string.Format("{0}({1}){2}", name, index, extension);
                path = Path.Combine(folderPath, temp);
                index++;
            }

            File.Copy(source, path, false);

            return Path.GetFileName(path);
        }

        public static decimal ConvertToDecimal(object value)
        {            
            var info = new CultureInfo(Constants.CultureInfo);
            return Convert.ToDecimal(value, info);
        }

        public static decimal ConvertToDecimal(string value)
        {            
            return Convert.ToDecimal(value);
        }

        public static string GetNumberValue(int? value, CultureInfo cultureInfo)
        {
            if (value.HasValue)
            {
                return value.Value.ToString(cultureInfo);
            }
            return string.Empty;
        }

        public static string GetDecimalValue(decimal? value, CultureInfo cultureInfo)
        {
            if (value.HasValue)
            {
                return value.Value.ToString(Constants.NumberFormat, cultureInfo);
            }
            return string.Empty;
        }

        public static string GetDecimalValue(decimal? value)
        {
            if (value.HasValue)
            {
                return value.Value.ToString("#,###");
            }
            return string.Empty;
        }

        public static decimal? GetNumberFieldValue(object numberValue)
        {
            decimal value = Convert.ToDecimal(numberValue);
            if (value > 0)
            {
                return value;
            }

            return null;
        }

        public static void CheckDirectory(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
        }

        public static string EncodePassword(string password)
        {
            byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(password);
            string encoded = Convert.ToBase64String(toEncodeAsBytes);

            return encoded;
        }

        public static string DecodedPassword(string encodedPassword)
        {
            byte[] encodedDataAsBytes = Convert.FromBase64String(encodedPassword);
            string password = Encoding.ASCII.GetString(encodedDataAsBytes);

            return password;
        }

        public static int ConvertInt(string value)
        {
            int number = 0;

            if (int.TryParse(value, out number))
            {
                return number;
            }

            return 0;
        }

        public static int GetPageNumber(string value, List<int> numbers)
        {
            if (string.IsNullOrEmpty(value))
            {
                return 0;
            }

            int number = 0;

            if (value.IndexOf(";") != -1 || value.IndexOf(",") != -1)
            {
                var arr = value.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var pageValue in arr)
                {
                    number += PageCount(pageValue, numbers);
                }
            }
            else
            {
                number = PageCount(value, numbers);
            }

            return number;
        }

        private static int PageCount(string pageValue, List<int> numbers)
        {
            if (!string.IsNullOrEmpty(pageValue))
            {
                var pages = pageValue.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                if (pages.Length == 2)
                {
                    int first = 0;
                    int last = 0;
                    if (pages[0].IndexOf(".") != -1)
                    {
                        var arr1 = pages[0].Split('.');
                        var arr2 = pages[1].Split('.');
                        if (arr1[0] == arr2[0])
                        {                            
                            first = ConvertInt(arr1[1]);
                            last = ConvertInt(arr2[1]);
                        }
                    }
                    else
                    {
                        first = ConvertInt(pages[0]);
                        last = ConvertInt(pages[1]);
                    }

                    if (first > 0 && last > 0)
                    {
                        numbers.Add(first);
                        numbers.Add(last);
                        return last - first + 1;
                    }
                }
                else
                {
                    if (pages[0].IndexOf(".") != -1)
                    {
                        var arr1 = pages[0].Split('.');
                        numbers.Add(ConvertInt(arr1[1]));
                    }
                    else
                    {
                        numbers.Add(ConvertInt(pages[0]));
                    }
                    return 1;
                }
            }

            return 0;
        }

        public static int GetSeletedItemIndex(RadListDataItemCollection items, int value)
        {
            foreach (var item in items)
            {
                int itemValue = Convert.ToInt32(item.Value);
                if (itemValue == value)
                    return item.RowIndex;
            }
            return -1;
        }

        public static string ConvertCurrency(decimal total, int level)
        {
            decimal source = total % 1000;

            int a = (int)(source / 100);
            int b = (int)((source % 100) / 10);
            int c = (int)(source % 10);

            string aValue = a > 0 ? string.Concat(ConvertNumberToString(a), " trăm ") : string.Empty;
            string bValue = b > 0 ? string.Concat(ConvertNumberToString(b), " mươi ") : string.Empty;
            string cValue = c > 0 ? string.Concat(ConvertNumberToString(c), " ") : string.Empty;

            if (a > 0 && b == 0 && c > 0)
            {
                bValue = "linh ";
            }

            decimal preValue = (total - source) / 1000;

            if (total > 0)
            {
                string temp = string.Format(" {0}{1}{2}{3}", aValue, bValue, cValue, GetCurrencyBase(level));
                temp = temp.Replace("mươi một", "mươi mốt");
                temp = temp.Replace("một mươi", "mười");
                string content = ConvertCurrency(preValue, ++level) + temp;
                return content;
            }

            return string.Empty;
        }

        private static string GetCurrencyBase(int level)
        {
            string currencyBase = string.Empty;
            switch (level)
            {
                case 1:
                    currencyBase = "đồng";
                    break;
                case 2:
                    currencyBase = "nghìn";
                    break;
                case 3:
                    currencyBase = "triệu";
                    break;
                default:
                    break;
            }

            return currencyBase;
        }

        private static string ConvertNumberToString(int number)
        {
            string value = string.Empty;

            switch (number)
            {
                case 0:
                    value = "không";
                    break;
                case 1:
                    value = "một";                    
                    break;
                case 2:
                    value = "hai";
                    break;
                case 3:
                    value = "ba";
                    break;
                case 4:
                    value = "bốn";
                    break;
                case 5:
                    value = "năm";
                    break;
                case 6:
                    value = "sáu";
                    break;
                case 7:
                    value = "bảy";
                    break;
                case 8:
                    value = "tám";
                    break;
                case 9:
                    value = "chín";
                    break;
            }

            return value;
        }
    }
}
